package com.app.micaihu.view.main.game.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;

import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.bean.game.GameRaidersContent;
import com.app.micaihu.bean.game.GameRaidersEntity;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.custom.components.downandupload.DownloadUtils;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.view.main.game.GameDetailActivity;
import com.app.micaihu.view.main.game.GameRaidersListActivity;
import com.app.micaihu.view.main.game.GameRaidersNewsActivity;
import com.app.micaihu.view.main.game.GameRaidersVideoActivity;
import com.app.micaihu.view.main.game.adapter.GameRaidersAdapter;
import com.app.micaihu.view.newsdetail.view.NewsDetailWebView;
import com.app.utils.util.AppTools;
import com.app.utils.util.image.LoadImageUtils;

import java.lang.reflect.InvocationTargetException;

/**
 * 游戏内容详情自定义View(文章攻略的)
 * Created by linkai on 2016/11/3.
 */
public class GameDetailNewsView extends NestedScrollView implements View.OnClickListener {

    /*********** 页面控件 *************/
    private TextView newsTitle;//文章标题
    private TextView newsTime;//新闻时间
    public NewsDetailWebView webview;//显示内容的容器
    private ListView aboutNewsListView;//相关新闻

    /*********** 逻辑数据 *************/
    private GameRaidersContent mNewsContent;
    private Context context;
    public String httpName;//数据请求的标识

    public GameDetailNewsView(Context context) {
        super(context);
        this.context = context;
    }

    public GameDetailNewsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }



    /**
     * 初始化控件
     */
    public void init() {
        inflate(getContext(), R.layout.view_game_detail_news, this);
        newsTitle = (TextView) findViewById(R.id.tv_newstitle);
        newsTime = (TextView) findViewById(R.id.tv_news_time);
        webview = (NewsDetailWebView) findViewById(R.id.cwv_webview);
    }


    /**
     * 加载新闻内容
     *
     * @param newscontent
     */
    public void setNewsData(GameRaidersContent newscontent) {

        this.mNewsContent = newscontent;

        //替换图片
        String content = webview.replaceImg(mNewsContent.getArticleContent());
        if(!TextUtils.isEmpty(content)){
            webview.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
        }
        this.newsTitle.setText(mNewsContent.getArticleTitle());
        this.newsTime.setText(mNewsContent.getPublishTime() + "时间");
    }

    /**
     * 继续播放视频
     */
    public void resumeWebview() {
        if (webview != null) {
            //继续播放视频
            try {
                webview.getClass().getMethod("onResume").invoke(webview, (Object[]) null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 停止webview
     */
    public void stopWebview() {
        if (this.webview != null) {
            //暂停视频
            this.webview.onPause();
            try {
                webview.getClass().getMethod("onPause").invoke(webview, (Object[]) null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 销毁webview
     */
    public void destoryWebview() {
        if (webview != null) {
            try {
                webview.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置相关新闻
     *
     */
    public void setAboutData(final String gameid) {
        if (mNewsContent != null) {
            // 0.5秒后显示
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    if(webview == null){
                        return;
                    }
                    //适配相关新闻部分
                    if(mNewsContent.getAboutList() != null &&mNewsContent.getAboutList().size() > 0){
                        aboutNewsListView = (ListView) findViewById(R.id.lv_aboutlist);
                        View btnGotoMore = LayoutInflater.from(AppApplication.getInstance()).inflate(R.layout.layout_textbtn_footer, null);
                        btnGotoMore.setOnClickListener(GameDetailNewsView.this);
                        btnGotoMore.setTag(gameid);
                        aboutNewsListView.addFooterView(btnGotoMore);
                        GameRaidersAdapter aboutAdapter = new GameRaidersAdapter(mNewsContent.getAboutList(), context,true);
                        aboutNewsListView.setAdapter(aboutAdapter);
                        aboutNewsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (mNewsContent.getAboutList() == null || context == null) {
                                    return;
                                }
                                //防止越界
                                if (position >= mNewsContent.getAboutList().size()) {
                                    position = mNewsContent.getAboutList().size() - 1;
                                } else if (position < 0) {
                                    position = 0;
                                }
                                GameRaidersEntity newsEntity = mNewsContent.getAboutList().get(position);
                                Intent intent = new Intent();
                                intent.putExtra(Config.Extra.PARAMETER1, newsEntity.getArticleId());
                                intent.putExtra(Config.Extra.PARAMETER2, newsEntity.getGameId());
                                if (TextUtils.equals(newsEntity.getArticleType(), TypeConstant.GAME_RAIDERS_TEXT)) {
                                    intent.setClass(context, GameRaidersNewsActivity.class);
                                } else if (TextUtils.equals(newsEntity.getArticleType(), TypeConstant.GAME_RAIDERS_VIDEO)) {
                                    intent.setClass(context, GameRaidersVideoActivity.class);
                                }
                                context.startActivity(intent);
                            }
                        });

                        //显示相关新闻部分
                        aboutNewsListView.setVisibility(View.VISIBLE);
                    }
                    //加载相关游戏
                    loadAboutGame();

                }
            }, 500);
            return;
        }

    }

    /**
     * 加载相关新闻
     */
    private void loadAboutGame(){
        //加载底部下载推广内容
        if(!TextUtils.isEmpty(mNewsContent.getInformTitle())){
            findViewById(R.id.indorlayout).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.informTitle)).setText(mNewsContent.getInformTitle());
            ((TextView) findViewById(R.id.informContent)).setText(mNewsContent.getInformContent());
            CustomImageView image = (CustomImageView) findViewById(R.id.inforicon);
            LoadImageUtils.getInstance().loadImage(image,mNewsContent.getAppIcon());
            ((TextView) findViewById(R.id.indorname)).setText(mNewsContent.getAppName());
            String downStr = "<font color='#FF8200'>"+mNewsContent.getDownloadNum()+"</font>人下载 "+mNewsContent.getAppSize();
            ((TextView) findViewById(R.id.infordesc)).setText(Html.fromHtml(downStr));
            findViewById(R.id.infordownload).setOnClickListener(this);
        }

        if(mNewsContent.getRelatedGame() != null && mNewsContent.getRelatedGame().size() > 0){
            //加载相关游戏
            findViewById(R.id.tv_about).setVisibility(View.VISIBLE);
            findViewById(R.id.hs_about_game).setVisibility(View.VISIBLE);
            LinearLayout llAboutGameContainer = (LinearLayout) findViewById(R.id.ll_about_game_container);
            for (int i = 0; i < mNewsContent.getRelatedGame().size(); i++) {
                RelatedGameView relatedGameView = new RelatedGameView(context, mNewsContent.getRelatedGame().get(i), i);
                relatedGameView.setOnClickListener(this);
                llAboutGameContainer.addView(relatedGameView);
            }
        }



    }


    @Override
    public void onClick(View v) {
        if (v == null || mNewsContent == null || context == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.btn_goto_more:
                if(v.getTag() == null){
                    return;
                }
                Intent intent1 = new Intent(context, GameRaidersListActivity.class);
                intent1.putExtra(Config.Extra.PARAMETER1, v.getTag().toString());
                context.startActivity(intent1);
                break;
            case R.id.infordownload:
                if(mNewsContent == null || context == null){
                    return;
                }
                if(mNewsContent.isinstall()){
                    //立即打开
                    AppTools.startUpApp(context, mNewsContent.getPackageName());
                    DownloadUtils.getSingleton().requestStatisticsInterface(this.mNewsContent.getGameId(), DownloadUtils.CLICKTYPE_STARTUP);
                }else{
                    //跳转内页
                    Intent intent = new Intent(context,GameDetailActivity.class);
                    intent.putExtra(Config.Extra.PARAMETER1,mNewsContent.getGameId());
                    context.startActivity(intent);
                }
                break;
            case R.id.relatedview:
                try {
                    if (context != null) {
                        RelatedGameView tag = (RelatedGameView) v;
                        String gameId = (String) tag.getTag();
                        Intent intent = new Intent();
                        intent.putExtra(Config.Extra.PARAMETER1, gameId);
                        intent.setClass(context, GameDetailActivity.class);
                        context.startActivity(intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }




}
